<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="学员" prop="userId">
        <el-select
          v-model="queryParams.userId"
          clearable
          filterable
          placeholder="请选择学员"
          class="!w-240px"
        >
          <el-option v-for="u in userOptions" :key="u.id" :label="u.nickname" :value="u.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="danger"
          plain
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
          v-hasPermi="['pm:userexam:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExportFinal"
          :loading="exportLoading"
          v-hasPermi="['pm:userexam:finalexport']"
        >
          <Icon icon="ep:download" class="mr-5px" />结果导出
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExportProcess"
          :loading="exportLoading"
          v-hasPermi="['pm:userexam:processexport']"
        >
          <Icon icon="ep:download" class="mr-5px" />详情导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="id" label="编号" align="center" width="80" />
      <el-table-column prop="userName" label="用户名" min-width="120" />
      <el-table-column prop="jobName" label="任务名" min-width="120" />
      <el-table-column prop="dimension" label="维度" min-width="100" />
      <el-table-column prop="storeName" label="题库名" min-width="120" />
      <el-table-column prop="round" label="答题轮次" align="center" width="100" />
      <el-table-column prop="finalScore" label="能力值" align="center" width="100" />
      <el-table-column prop="finalSem" label="偏离值" align="center" width="100" />
      <el-table-column prop="endFlag" label="是否完成" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.endFlag === 1 ? 'success' : 'info'">{{
            scope.row.endFlag === 1 ? '已完成' : '未完成'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="timeSpent" label="耗时(秒)" align="center" width="100" />
      <el-table-column prop="maxNi" label="答题数" align="center" width="100" />
      <el-table-column prop="maxSe" label="终止阈值" align="center" width="100" />
      <el-table-column prop="createTime" label="创建时间" :formatter="dateFormatter" width="180" />
      <el-table-column prop="endTime" label="结束时间" :formatter="dateFormatter" width="180" />
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import * as UserExamApi from '@/api/pm/userexam'
import * as UserApi from '@/api/pm/user'
import { dateFormatter } from '@/utils/formatTime'

defineOptions({ name: 'PmUserExam' })

const message = useMessage()

const loading = ref(true)
const total = ref(0)
const list = ref<any[]>([])
const queryFormRef = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined as number | undefined
})
const exportLoading = ref(false)
const userOptions = ref<any[]>([])
const selectedIds = ref<number[]>([])

const getList = async () => {
  loading.value = true
  try {
    const data: any = await UserExamApi.getUserExamPage({
      page: queryParams.pageNo,
      limit: queryParams.pageSize,
      userId: queryParams.userId
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields?.()
  handleQuery()
}

const handleExportProcess = async () => {
  try {
    exportLoading.value = true
    const res = await UserExamApi.exportProcess(queryParams)
    download.excel(res as unknown as Blob, '答题详情导出.xls')
  } finally {
    exportLoading.value = false
  }
}

const handleExportFinal = async () => {
  try {
    exportLoading.value = true
    const res = await UserExamApi.exportFinal(queryParams)
    download.excel(res as unknown as Blob, '最终结果导出.xls')
  } finally {
    exportLoading.value = false
  }
}

const onSelectionChange = (rows: any[]) => {
  selectedIds.value = rows.map((r) => r.id)
}

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) return
  try {
    await message.delConfirm()
    await UserExamApi.batchDeleteUserExam(selectedIds.value)
    message.success('删除成功')
    selectedIds.value = []
    await getList()
  } catch {}
}

onMounted(async () => {
  try {
    const users = await UserApi.getUserQuery()
    userOptions.value = users || []
  } catch {}
  getList()
})
</script>
